package com.honghh.controller;

import com.honghh.entity.User;
import com.honghh.repository.UserRepository;
import com.honghh.utils.CookieUtils;
import com.honghh.utils.JwtUtils;
import com.honghh.variable.EnvVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;

/**
 * description:
 *
 * @author: hh
 * @date: 2018/6/8 10:51
 */
@Controller
public class LoginController {

    @Autowired
    UserRepository userRepository;

    @Autowired
    EnvVariable envVariable;

    @RequestMapping("/")
    public String home() {
        return "redirect:/login";
    }


    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(HttpServletResponse httpServletResponse, String username, String password, String redirect, Model model) {

        User user = userRepository.findByUsername(username);

        if (user == null || !password.equals(user.getPassword())) {
            model.addAttribute("error", "输入的账号或密码不正确");
            return "login";
        }

        String token = JwtUtils.generateToken(envVariable.getSigningKey(), username);

        CookieUtils.create(httpServletResponse, envVariable.getJwtTokenCookieName(), token, false, -1, envVariable.getCookieParentDomain());

        model.addAttribute("user", user);
        return "index";
    }
}
